package com.ldcc.report_system.ui;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.res.ResourcesCompat;

import com.ldcc.report_system.ApplicationConfig;
import com.ldcc.report_system.R;
import com.ldcc.report_system.ReportApplication;
import com.ldcc.report_system.api.param.LoginParam;
import com.ldcc.report_system.api.results.LoginResults;
import com.ldcc.report_system.api.results.User;
import com.ldcc.report_system.databinding.ActivityLoginBinding;
import com.ldcc.report_system.ui.setting.NetWorkSettingActivity;
import com.ldcc.report_system.util.ActivitySkipUtil;
import com.ldcc.report_system.util.AlertUtil;
import com.ldcc.report_system.util.LoadingUtil;
import com.ldcc.report_system.util.ServerUtil;
import com.ldcc.report_system.util.SharedPreferencesUtils;
import com.ldcc.report_system.util.WindowUtils;
import com.ldcc.report_system.util.http.ClientRequestManage;
import com.ldcc.report_system.util.http.HttpObserver;
import com.ldcc.report_system.util.http.ServerResponse;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author wwj[yeshengkele@outlook.com]
 * @description 登录界面
 */
public class LoginActivity extends AppCompatActivity {
    public static final String TAG = "LoginActivity";
    private ActivityLoginBinding loginBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.loginBinding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(this.loginBinding.getRoot());
        // 设置界面顶部为透明
        WindowUtils.setWindowTopTransparent(getWindow());
        this.initPage();
        this.setListener();
    }


    /***
     * @description 初始化页面
     */
    private void initPage() {

        // 设置 图标大小
        Drawable usernameIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.input_username, null);
        if (usernameIcon != null) {
            //第一个 0 是距左边距离，第二个 0 是距上边距离，45 分别是长宽
            usernameIcon.setBounds(0, 0, 45, 48);
            this.loginBinding.loginUserNameValue.setCompoundDrawables(usernameIcon, null, null, null);
        }
        Drawable passwordIcon = ResourcesCompat.getDrawable(getResources(), R.drawable.input_password, null);
        if (passwordIcon != null) {
            passwordIcon.setBounds(0, 0, 45, 48);
            this.loginBinding.loginPasswordValue.setCompoundDrawables(passwordIcon, null, null, null);
        }


    }

    /**
     * @description 设置点击事件
     */
    private void setListener() {
        // 跳转网络设置界面
        this.loginBinding.settingBtn.setOnClickListener(view -> {
            ActivitySkipUtil.skipAnotherActivity(this, NetWorkSettingActivity.class);
        });
        // 登录点击事件
        this.loginBinding.loginBtn.setOnClickListener(view -> {
            // 检测网络配置是否存在
            if (!ServerUtil.checkServerUrl()) {
                AlertUtil.shortTime("请配置网络");
                return;
            }
            LoginParam loginPram = new LoginParam() {{
                setUsername(loginBinding.loginUserNameValue.getText().toString());
                setPassword(loginBinding.loginPasswordValue.getText().toString());
            }};
            if ("".equals(loginPram.getPassword()) || "".equals(loginPram.getUsername())) {
                AlertUtil.shortTime("请输入用户名和密码");
            } else {
                // 设置发送请求
                Log.e(TAG, loginPram.toString());
                ClientRequestManage.getInstance().getUserApi().login(loginPram).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new HttpObserver<LoginResults>(ReportApplication.getContext(),
                                LoadingUtil.dialogLoadingOpen("请稍后", "正在连接服务器....", this)) {
                            @Override
                            public void onSuccess(ServerResponse<LoginResults> response_entity) {
                                String token = response_entity.getData().getToken();
                                // 请求成功
                                AlertUtil.shortTime("登录成功");
                                // 1. 存放token
                                Context context = ReportApplication.getContext();
                                SharedPreferencesUtils.setParam(context, ApplicationConfig.USER_TOKEN_KEY, token);
                                User user = response_entity.getData().getUser().getUser();
                                // 保存userId
                                SharedPreferencesUtils.setParam(context, ApplicationConfig.USER_ID_KEY, user.getId());
                                // 2. 不带参数跳转页面
                                ActivitySkipUtil.skipAnotherActivity(LoginActivity.this, MainActivity.class);
                            }
                        });
            }
        });
    }


}